package com.book.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.enums.UserEnum;
import com.book.mapper.AuthorMapper;
import com.book.mapper.ReadersMapper;
import com.book.model.Author;
import com.book.model.Readers;
import com.book.service.ReadersService;
import com.book.token.UserToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private AuthorMapper authorMapper;

    @Autowired
    private ReadersService readersService;

    @Autowired
    private ReadersMapper readersMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //拦截到controller认证请求
        UserToken token = (UserToken) authenticationToken;
        UserEnum userEnum = token.getUserEnum();

        //判断作者
        if(Objects.equals(userEnum,UserEnum.ADMIN)){
            QueryWrapper<Author> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username",token.getUsername());
            Author author = authorMapper.selectOne(queryWrapper);
            if(author==null){
                return null;
            }
            SimpleAuthenticationInfo sim1 = new SimpleAuthenticationInfo(author, author.getPassword(), ByteSource.Util.bytes(author.getSalt()), "userRealm");
            return sim1;
        //判断读者
        }else if(Objects.equals(userEnum,UserEnum.SELLER)){
            QueryWrapper<Readers> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username",token.getUsername());
            Readers readers = readersMapper.selectOne(queryWrapper);
            if(readers==null){
                return null;
            }
            SimpleAuthenticationInfo sim2 = new SimpleAuthenticationInfo(readers, readers.getPassword(), ByteSource.Util.bytes(readers.getSalt()), "userRealm1");
            return sim2;
        }

        System.out.println("执行认证逻辑");

        return null;
    }
}
